import { useParams, useNavigate } from 'react-router-dom'
import { Menu, Modal, message, Upload } from 'antd'
import { LogoutOutlined, PlusOutlined } from '@ant-design/icons'
import { useAuth } from '@/utils/auth'
import { useState } from 'react'
import { $api } from '@/http/api'

const ManagerHeader = (props) => {
  const [fileList, setFileList] = useState([]);
  const [previewVisible, setPreviewVisible] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [previewTitle, setPreviewTitle] = useState('');
  const [isModalVisible, setIsModalVisible] = useState(false);

  const showModal = () => {
    setIsModalVisible(true);
  };

  const handleOk = () => {
    if (fileList[0] === undefined) {
      message.error("Please select a picture!")
    } else {
      $api.manager.restaurantPicture({
        id: params.id,
        file: fileList[0].originFileObj
      }).then((res) => {
        if (res.code === 200) {
          message.success("Set restaurant picture successfully!")
          setFileList([])
          handleCancel()
        }
      })
    }
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  const { signOut, setNewSignUp } = useAuth()

  const { name } = props

  const navigate = useNavigate()

  const params = useParams()

  const navs = [
    {
      label: 'Orders',
      key: `/manager/${params.id}/orders`,
    },
    {
      key: `/manager/${params.id}/menu`,
      label: 'Menu'
    }
  ]

  const onNavSelect = (item) => {
    navigate(item.key)
  }

  const logout = () => {
    signOut()
    navigate('/login')
  }

  const home = () => {
    navigate('/')
  }

  const getBase64 = (file) => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = error => reject(error);
    });
  }

  const handlePreview = async file => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }
    setPreviewImage(file.url || file.preview)
    setPreviewTitle(file.name || file.url.substring(file.url.lastIndexOf('/') + 1))
    setPreviewVisible(true)
  };

  const cancelPreview = () => setPreviewVisible(false)

  const uploadProps = {
    beforeUpload: file => {
      const isIMG = file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'image/jpeg';
      if (!isIMG) {
        message.error(`${file.name} is not a image file`);
      }
      return false
    },
    listType: "picture-card"
  }
  const uploadButton = (
    <div>
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  )

  const handleChange = ({ fileList }) => setFileList(fileList)

  return (
    <>
      <div className='flex-between h-full px-4 sm:px-8 lg:px-12'>
        <div className='flex-start'>
          <div className='w-48 text-3xl leading-none cursor-pointer' onClick={home}>TAKAWAY</div>
          <div className='w-48 shrink-0'>
            <Menu mode='horizontal' items={navs} onSelect={onNavSelect} />
          </div>
        </div>
        <div className='flex-end'>
          <div className='hidden sm:block bg-slate-500 text-white rounded-full h-10 leading-10 px-5 mx-5 cursor-pointer' onClick={showModal}>{name}</div>
          <LogoutOutlined className='bg-slate-500 rounded-full' style={{
            color: '#FFF',
            fontSize: '150%',
            padding: '9.5px'
          }} onClick={logout} />
        </div>
      </div>
      <Modal title="Set Restaurant Picture" visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
        <Upload fileList={fileList} {...uploadProps} maxCount={1} onChange={handleChange} onPreview={handlePreview}>
          {fileList.length > 0 ? null : uploadButton}
        </Upload>
      </Modal>
      <Modal
        visible={previewVisible}
        title={previewTitle}
        footer={null}
        onCancel={cancelPreview}>
        <img alt="example" style={{ width: '100%' }} src={previewImage} />
      </Modal>
    </>
  )
}

export default ManagerHeader